package com.assistant.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.assistant.common.DateUtil;
import com.assistant.wechat.pojo.Message;
import com.assistant.wechat.pojo.WxUser;
import com.assistant.wechat.service.WxUserService;
import com.assistant.wechat.service.impl.MessageServiceImpl;
import com.assistant.wechat.util.MapUnite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  描述:
 *  一对一聊天
 */
@RestController
@ServerEndpoint(value = "/webSocketOneToOne/{param}")
public class WebSocketController {

    private static  MessageServiceImpl messageService;
    @Autowired
    public void setMessgeServiceImpl(MessageServiceImpl messageService){
        WebSocketController.messageService = messageService;
    }


    private static  WxUserService wxUserService;
    @Autowired
    public void setWxUserService(WxUserService wxUserService) {
        WebSocketController.wxUserService = wxUserService;
    }


    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount;
    //实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key为用户标识
    private static final Map<String, WebSocketController> connections = new ConcurrentHashMap<>();
    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private String sendId;
    private String roomId;


    @OnOpen
    public void onOpen(@PathParam("param") String param, Session session) {
        this.session = session;
        String[] arr = param.split(",");
        this.sendId = arr[0];             //用户标识
        this.roomId = arr[1];         //会话标识
        connections.put(sendId,this);     //添加到map中
        addOnlineCount();               // 在线数加
        System.out.println(param);
        System.out.println(this.session);
        System.out.println("有新连接加入！新用户："+sendId+",当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        connections.remove(sendId);  // 从map中移除
        subOnlineCount();          // 在线数减
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }


    @OnMessage
    public void onMessage(String message, Session session) {
        JSONObject json= JSON.parseObject(message);
        String msg = (String) json.get("message");  //需要发送的信息
        String receiveId = (String) json.get("receiveId");      //发送对象的用户标识(接收者)//发送对象的用户标识(接收者)
        send(msg,sendId,receiveId,roomId);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    //发送给指定角色
    public void send(String msg, String sendId, String receiveId, String roomId){
        Message message = new Message();
        message.setContent(msg);
        message.setCreate_time(DateUtil.dataFormatUtil(new Date()));
        message.setReceive_id(receiveId);
        message.setRoom_id(roomId);
        message.setSend_id(sendId);
        try {
            List<WxUser> list = wxUserService.getWxuserById(sendId);
            WxUser u  = list.get(0);
            //to指定用户
            WebSocketController con = connections.get(receiveId);
            if(con!=null){
                if(roomId.equals(con.roomId)){
                    System.out.println(message);
//                    messageService.insertMessage(message);
                    Map map = MapUnite.getMap(message);
                    map.put("avatar",u.getAvatar_url());
                    System.out.println("to指定用户");
                    con.session.getBasicRemote().sendText(JSON.toJSONString(map));
                }

            }
            //from具体用户
            WebSocketController confrom = connections.get(sendId);
            if(confrom!=null){
                if(roomId.equals(confrom.roomId)){
                    System.out.println(message);
//                    messageService.insertMessage(message);
                    Map map = MapUnite.getMap(message);
                    map.put("avatar",u.getAvatar_url());
                    System.out.println("从指定用户发");
                    confrom.session.getBasicRemote().sendText(JSON.toJSONString(map));
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketController.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketController.onlineCount--;
    }

}
